<template>
  <div>
    <Dialog
      :title="title"
      :model-value="visible"
      width="1000px"
      max-height="700px"
      :before-close="closeForm"
    >
      <div style="width: 100%">
        <Search
          ref="search"
          :schema="scheme"
          :model="queryParam"
          :is-col="false"
          layout="inline"
          :showSearch="true"
          button-position="left"
          :search-loading="loading"
          :reset-loading="loading"
          @search="handleSearch"
          @reset="handleSearch"
        >
          <template #opts>
            <BaseButton type="success" v-hasPermi="'add'" @click="addItem">添加字典项</BaseButton>
          </template>
        </Search>
      </div>
      <Table :data="items" :columns="columns" max-height="500px" @change="load">
        <template #DicStatus="e">
          <el-switch
            v-model="e.row.DicStatus"
            :disabled="$hasPermi('set') == false"
            :inactive-value="e.row.DicStatus == 1 ? 2 : 0"
            :active-value="1"
            @change="(value) => setStatus(e.row, value)"
          />
        </template>
        <template #Sort="e">
          <el-space>
            <BaseButton
              v-if="e.row.Sort != 1"
              :icon="topIcon"
              size="small"
              circle
              @click="upItem(e.row)"
            />
            <BaseButton
              v-if="e.row.Sort != maxSort"
              size="small"
              :icon="bottomIcon"
              circle
              @click="downItem(e.row, e.index)"
            />
          </el-space>
        </template>
        <template #action="e">
          <BaseButton
            v-hasPermi="'set'"
            size="small"
            type="warning"
            title="编辑"
            :icon="editIcon"
            circle
            @click="editItem(e.row)"
          />
          <BaseButton
            v-hasPermi="'delete'"
            v-if="e.row.DicStatus == 0"
            size="small"
            type="danger"
            title="删除"
            :icon="dropIcon"
            circle
            @click="deleteItem(e.row)"
          />
        </template>
      </Table>
    </Dialog>
    <editDicItem :id="id" v-model:visible="visibleEdit" :dic-id="dicId" @close="closeEdit" />
  </div>
</template>

<script>
import * as dicItemApi from '@/api/base/dictItem'
import { HrEnumDic } from '@/config/publicDic'
import { Dialog } from '@/components/Dialog'
import { Search } from '@/components/Search'
import { Table } from '@/components/Table'
import { useIcon } from '@/hooks/web/useIcon'
import { OrderBy } from '@/utils/index'
import editDicItem from './components/editDicItem.vue'
import { hasPermission } from '@/directives/permission/hasPermi'
export default {
  name: 'DicItem',
  components: {
    Search,
    Dialog,
    Table,
    editDicItem
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    dicName: {
      type: String,
      default: null
    },
    dicId: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      loading: false,
      topIcon: useIcon({ icon: 'ep:top' }),
      bottomIcon: useIcon({ icon: 'ep:bottom' }),
      editIcon: useIcon({ icon: 'ep:edit' }),
      dropIcon: useIcon({ icon: 'ep:delete' }),
      scheme: [
        {
          field: 'QueryKey',
          label: '关键字',
          component: 'Input',
          componentProps: {
            placeholder: '关键字'
          }
        },
        {
          field: 'Status',
          label: '字典项状态',
          component: 'EnumItem',
          componentProps: {
            dicKey: HrEnumDic.dicItemStatus,
            placeholder: '字典项状态',
            multiple: true
          }
        }
      ],
      items: [],
      visibleEdit: false,
      maxSort: 1,
      minSort: 1,
      id: null,
      title: '字典',
      columns: [
        {
          sortby: 'DicText',
          field: 'DicText',
          label: '字典文本',
          align: 'left',
          minWidth: 150,
          sortable: 'custom'
        },
        {
          field: 'DicValue',
          label: '字典值',
          align: 'left',
          minWidth: 200
        },
        {
          sortby: 'DicStatus',
          field: 'DicStatus',
          label: '状态',
          align: 'center',
          slotName: 'DicStatus',
          minWidth: 100,
          sortable: 'custom'
        },
        {
          sortby: 'Sort',
          field: 'Sort',
          label: '排序',
          align: 'center',
          slotName: 'Sort',
          hidden: hasPermission('set') == false,
          minWidth: 100,
          sortable: 'custom'
        },
        {
          field: 'Action',
          label: '操作',
          align: 'left',
          hidden: hasPermission('set') == false && hasPermission('delete') == false,
          fixed: 'right',
          width: '140px',
          slotName: 'action'
        }
      ],
      queryParam: {
        DicId: null,
        QueryKey: null,
        Status: null
      }
    }
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.reset()
        }
      },
      immediate: true
    }
  },
  mounted() {},
  methods: {
    closeEdit(isRefresh) {
      if (isRefresh) {
        this.reset()
      }
    },
    handleSearch(data) {
      this.queryParam.QueryKey = data.QueryKey
      this.queryParam.Status = data.Status
      this.load()
    },
    editItem(row) {
      this.id = row.Id
      this.parent = null
      this.visibleEdit = true
    },
    async reset() {
      this.title = '字典' + this.dicName + '明细'
      this.queryParam.DicId = this.dicId
      this.queryParam.QueryKey = null
      this.queryParam.Status = null
      this.load()
    },
    upItem(row) {
      const to = this.items[row.index - 1]
      this.moveLoad(row, to)
    },
    async moveLoad(form, to) {
      await dicItemApi.Move(form.Id, to.Id)
      const sort = form.Sort
      const index = form.index
      form.index = to.index
      form.Sort = to.Sort
      to.Sort = sort
      to.index = index
      this.items = OrderBy(this.items, 'Sort')
    },
    downItem(row) {
      const to = this.items[row.index + 1]
      this.moveLoad(row, to)
    },
    addItem(row) {
      this.id = null
      this.parent = row
      this.visibleEdit = true
    },
    deleteItem(row) {
      const title = '确认删除字典项 ' + row.DicText + '?'
      this.$confirm(title, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.submitDrop(row.Id)
      })
    },
    async setStatus(row, status) {
      if (status == 1) {
        await dicItemApi.Enable(row.Id)
      } else {
        await dicItemApi.Stop(row.Id)
      }
      row.DicStatus = status
    },
    async submitDrop(id) {
      await dicItemApi.DeleteItem(id)
      this.$message({
        type: 'success',
        message: '删除成功!'
      })
      this.load()
    },
    async load() {
      this.queryParam.DicId = this.dicId
      this.items = await dicItemApi.GetItems(this.queryParam)
      let index = 0
      let max = 0
      let min = Number.Max
      this.items.forEach((c) => {
        c.index = index
        index = index + 1
        if (c.Sort > max) {
          max = c.Sort
        }
        if (c.Sort < min) {
          min = c.Sort
        }
      })
      this.maxSort = max
      this.minSort = min
      this.loading = false
    },
    closeForm() {
      this.$emit('update:visible', false)
      this.$emit('close', false)
    }
  }
}
</script>
